package com.sgq.vue.service.resource.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sgq.vue.dao.resource.CityMapper;
import com.sgq.vue.entity.resource.City;
import com.sgq.vue.enums.RequestConditionEnums;
import com.sgq.vue.listener.ExcelListener;
import com.sgq.vue.service.resource.CityService;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: 83778
 * @date: 2023-12-19 17:18
 * @desc:
 */
@Service
public class CityServiceImpl extends ServiceImpl<CityMapper, City> implements CityService {



    @Override
    public List<City> findCityByProvinceName(City city) {
        LambdaQueryWrapper<City> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(City::getProvinceEn, city.getProvinceEn())
                    .or()
                    .eq(City::getProvinceZh, city.getProvinceZh())
                    .orderByAsc(City::getId);
        return this.baseMapper.selectList(queryWrapper);
    }

    /***
     * 通过父亲节点的leaderCode找到所有的孩子
     * @param leaderCode
     * @return
     */
    @Override
    @Cacheable(cacheNames = "city", key = "'cityId'+ #leaderCode")
    public List<City> findCityByLeaderCode(Long leaderCode) {
        LambdaQueryWrapper<City> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(City::getLeaderCode,leaderCode);
        List<City> cities = this.baseMapper.selectList(queryWrapper);
        cities.stream().forEach(city -> {
            Long id = city.getId();
            boolean b = this.hasChildren(id);
            city.setHasChildren(b);
        });
        return cities;
    }


    @Override
    public void exportCity(HttpServletResponse response) {

        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("城市字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            List<City> list = this.baseMapper.selectList(new QueryWrapper<>());

            EasyExcel.write(response.getOutputStream(), City.class).sheet("城市字典").doWrite(list);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    @Override
    @CacheEvict(cacheNames = "city", key = "'cityId'+ #leaderCode", allEntries = true)
    public void importCity(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),City.class,new ExcelListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    private boolean hasChildren(Long leaderCode){
        LambdaQueryWrapper<City> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(City::getLeaderCode,leaderCode);
        Long count = this.baseMapper.selectCount(queryWrapper);
        return count > 0;
    }
}
